const app = getApp();

Page({
  data: {
    reservations: [],
    loading: false,
    page: 0,
    size: 10,
    hasMore: true,
    status: null,
    statusOptions: [
      { value: null, label: '全部' },
      { value: 'PENDING', label: '待确认' },
      { value: 'CONFIRMED', label: '已确认' },
      { value: 'COMPLETED', label: '已完成' },
      { value: 'CANCELLED', label: '已取消' }
    ],
    currentStatus: 0
  },
  
  onLoad: function(options) {
    // 检查登录状态
    if (!app.globalData.token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadReservations(true);
  },
  
  onShow: function() {
    // 检查登录状态
    if (!app.globalData.token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 每次显示页面时刷新数据
    this.loadReservations(true);
    
    // 更新自定义tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      });
    }
  },
  
  onPullDownRefresh: function() {
    this.loadReservations(true);
  },
  
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadReservations(false);
    }
  },
  
  // 切换预约状态
  switchStatus: function(e) {
    const index = e.currentTarget.dataset.index;
    const status = this.data.statusOptions[index].value;
    
    this.setData({
      currentStatus: index,
      status: status,
      page: 0,
      hasMore: true,
      reservations: []
    });
    
    this.loadReservations(true);
  },
  
  // 加载预约数据
  loadReservations: function(refresh) {
    if (this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    if (refresh) {
      this.setData({
        page: 0,
        reservations: []
      });
      wx.showNavigationBarLoading();
    }
    
    let url = '/reservations/my';
    if (this.data.status) {
      url += `?status=${this.data.status}&page=${this.data.page}&size=${this.data.size}`;
    } else {
      url += `?page=${this.data.page}&size=${this.data.size}`;
    }
    
    app.request({
      url: url
    }).then(res => {
      // 转换后端返回的数据格式
      const reservations = res.content.map(item => {
        return {
          id: item.id,
          status: item.status,
          checkedIn: item.checkedIn,
          price: item.price,
          createdAt: item.createdAt,
          schedule: {
            id: item.schedule.id,
            date: item.schedule.date,
            departureTime: item.schedule.departureTime,
            arrivalTime: item.schedule.arrivalTime,
            routeDirection: item.schedule.routeDirection
          },
          payment: item.payment ? {
            id: item.payment.id,
            status: item.payment.status,
            paymentMethod: item.payment.paymentMethod
          } : null
        };
      });
      
      this.setData({
        reservations: refresh ? reservations : this.data.reservations.concat(reservations),
        page: this.data.page + 1,
        hasMore: res.totalPages > (this.data.page + 1),
        loading: false
      });
      
      if (refresh) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    }).catch(err => {
      this.setData({
        loading: false
      });
      
      if (refresh) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
      
      wx.showToast({
        title: err.message || '加载失败',
        icon: 'none'
      });
    });
  },
  
  // 查看预约详情
  viewReservationDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/reservation-detail/reservation-detail?id=${id}`
    });
  },
  
  // 取消预约
  cancelReservation: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '取消预约',
      content: '确定要取消这个预约吗？',
      success: (res) => {
        if (res.confirm) {
          this.performCancelReservation(id);
        }
      }
    });
  },
  
  // 执行取消预约
  performCancelReservation: function(id) {
    wx.showLoading({
      title: '取消中...',
    });
    
    app.request({
      url: `/reservations/${id}/cancel`,
      method: 'POST'
    }).then(() => {
      wx.hideLoading();
      wx.showToast({
        title: '取消成功',
        icon: 'success'
      });
      
      // 刷新列表
      this.loadReservations(true);
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '取消失败',
        icon: 'none'
      });
    });
  }
}) 